window.app = {
	serverAddress: "http://192.168.1.4:8080",

	imageServerAddress: "http://192.168.1.7/chat/",

	nettyServerAddress: "ws://192.168.1.4:12345/ws",

	getFaceThumbnailUrl: function(id, w, h) {
		if (w == 0 || h == 0) {
			return app.imageServerAddress + '/' + id + '.jpg_' + Math.random();
		} else {
			return app.imageServerAddress + '/' + id + '.jpg_' + w + 'x' + h + '?' +
				Math.random();
		}
	},
	
	setGlobalUserInfo: function(data) {
		plus.storage.setItem("user", JSON.stringify(data));
	},
	getGlobalUserInfo: function() {
		return JSON.parse(plus.storage.getItem("user"));
	},
	setFriendRequestList: function(data) {
		plus.storage.setItem("friend_request_list", "" + data);
	},
	getFriendRequestList: function() {
		return plus.storage.getItem("friend_request_list");
	},
	saveFriendList: function(data) {
		plus.storage.setItem("friend_list", JSON.stringify(data));
	},
	getFriendList: function() {
		return JSON.parse(plus.storage.getItem("friend_list"));
	},
	getFriendItem: function(id) {
		for (let item of app.getFriendList()) {
			if (item.id == id) return item;
		}

		return null;
	},
	getFaceImage: function(id) {
		return plus.storage.getItem(id.toString());
	},

	CONNECT: 1,
	CHAT: 2,
	SIGNED: 3,
	KEEPALIVE: 4,

	ChatMsg: function(senderId, receiverId, msg, msgId) {
		this.senderId = senderId;
		this.receiverId = receiverId;
		this.msg = msg;
		this.msgId = msgId;
	},

	DataContent: function(action, chatMsg, extras) {
		this.action = action;
		this.chatMsg = chatMsg;
		this.extras = extras;
	},

	ChatSnapshot: function(friendId, msg, unreadMsgCount) {
		this.friendId = friendId;
		this.msg = msg;
		this.unreadMsgCount = unreadMsgCount;
	},

	saveChatSnapshot: function(myId, friendId, msg, isRead) {
		var key = 'chat-snapshot-' + myId;
		var chatSnapshotListStr = plus.storage.getItem(key);
		var chatSnapshotList = [];
		var chatSnapshot = null;
		if (chatSnapshotListStr != null &&
			chatSnapshotListStr != undefined &&
			chatSnapshotListStr != "") {
			chatSnapshotList = JSON.parse(chatSnapshotListStr);
			for (var i = 0; i < chatSnapshotList.length; i++) {
				if (chatSnapshotList[i].friendId == friendId) {
					chatSnapshot = chatSnapshotList[i];
					chatSnapshotList.splice(i, 1);
					break;
				}
			}
		}

		if (chatSnapshot == null) {
			chatSnapshot = new app.ChatSnapshot(friendId, msg, isRead ? 0 : 1);
		} else {
			chatSnapshot.msg = msg;
			if (isRead) {
				chatSnapshot.unreadMsgCount++;
			} else {
				chatSnapshot.unreadMsgCount = 0;
			}
		}

		chatSnapshotList.unshift(chatSnapshot);
		plus.storage.setItem(key, JSON.stringify(chatSnapshotList));
	},

	getSnapshortList: function(myId) {
		var key = 'chat-snapshot-' + myId;
		var chatSnapshotListStr = plus.storage.getItem(key);

		var chatSnapshotList = [];
		if (chatSnapshotListStr != null &&
			chatSnapshotListStr != undefined &&
			chatSnapshotListStr != "") {
			chatSnapshotList = JSON.parse(chatSnapshotListStr);
		}

		return chatSnapshotList;
	}
};
